# Create your views here.
from django.conf import settings
from django.contrib.auth.decorators import login_required
from kalapankki.album.models import Album, Picture, Page
from django.db.models import Q
from kalapankki.album import forms
from django.core.urlresolvers import reverse
from django.http import Http404
from django.views.generic.simple import redirect_to 
from kalapankki import utils
from kalapankki.utils import get_page_number, get_pages, render_with_request_context
import string
import random
import os
import urllib
import urllib2

def show_albums(request, public_only=False):
    if utils.is_active_authenticated_user(request) and not public_only:
        albums = Album.objects.filter(owner= request.user)
    else:
        albums = Album.objects.filter(public=True)
    return utils.render_with_request_context(request, 'albums.html',{'albums' : albums})

@login_required
def show_pictures(request, picture_id=None):
    if picture_id is None:
        pictures = Picture.objects.filter(owner=request.user)
        return utils.render_with_request_context(request, 'all_pictures.html', {'pictures':pictures})
    
    picture = Picture.objects.get(owner=request.user,id=picture_id)
    return utils.render_with_request_context(request, 'show_picture.html', {'picture':picture})

def show(request, album_id, page_number=1):
    try:
        if utils.is_active_authenticated_user(request):
            album = Album.objects.get(Q(owner=request.user) | Q(public=True), id=album_id)
        elif request.GET.get('public_token') is not None:
            #make sure it's a string
            public_token = str(request.GET.get('public_token'))
            album = Album.objects.get(public_token=public_token)
        else:
            album = Album.objects.get(public=True, id=album_id)
    except Album.DoesNotExist:
        raise Http404
    
    #create the context data, going to the pages the user is currently at
    pages = utils.get_pages(request, album.page_set, page_number)
    rcontext = {'album':album, 'pages':pages}
        
    if album.public_token:
        #add the public token link to render removal choice
        rcontext['public_token_link'] = request.build_absolute_uri(reverse("show_album", kwargs={'album_id':album.id})) + "?public_token=%s" % album.public_token
                     
    if request.is_ajax():
        #an ajax request should only render the pages
        return utils.render_with_request_context(request,'album_pages.html', rcontext)
                     
    return utils.render_with_request_context(request, 'album_details.html', rcontext)
        
@login_required
def remove(request, album_id, page_id=None, picture_id=None):
    try:
        album = Album.objects.get(owner=request.user, id=album_id)
    except Album.DoesNotExist:
        raise Http404("Could not find the album")
    
    if page_id:
        #get the page from album
        try:
            page = album.page_set.get(id=page_id)
        except Album.DoesNotExist:
            raise Http404("Could not find the page from the album")
        
        #get the page number here since the page could be deleted
        page_num = get_page_number(album.page_set.all(), page)
        
        if picture_id:
            #remove the picture from the given page
            try:
                picture = page.picture_set.get(id=picture_id)
                picture.pages.remove(page)
            except Picture.DoesNotExist:
                raise Http404('Picture not found')
        else:
            #clear the pictures from the page but do not remove them
            page.picture_set.clear()
            page.delete()
        
        #get the template to render, on Ajax only the content needs to be re-rendered
        if request.is_ajax():
            #if an ajax request then only return the changed part
            #get the current page set
            pages = utils.get_pages(request, album.page_set, page_num)
            rcontext = {'album':album, 'pages':pages}
            return utils.render_with_request_context(request, 'album_pages.html', rcontext)
        else:
            #redirect to the album page to enable the url staying constant and refreshable
            return redirect_to(request, reverse('show_page',kwargs={'album_id':album.id, 'page_number':page_num}), False) 
    
    else:
        #delete all pages in the album and then delete the album itself
        for page in album.page_set.all():
            #only remove the pictures, not delete them
            page.picture_set.clear()
            page.delete()
        album.delete()
        
        return redirect_to(request, reverse('show_albums'), False)
            
@login_required
def add(request, album_id=None, page_id=None, picture_id=None):
    rcontext = {}
    if album_id and page_id and picture_id:
        try: 
            album=Album.objects.get(owner=request.user, id=album_id)
            page = album.page_set.get(id=page_id)
            picture = Picture.objects.get(owner=request.user, id=picture_id)
            picture.pages.add(page)
            picture.save()
            page_num = utils.get_page_number(album.page_set.all(), page)
            print "Page number %d " % page_num 
            return redirect_to(request,reverse('show_page', kwargs={'album_id':album.id,'page_number':page_num}), False)
        except (Album.DoesNotExist, Page.DoesNotExist):
            raise Http404("Could not find the album or page requested")
    
    elif album_id and page_id:
        #add a picture to a page and show that page from the album 
        pictures = Picture.objects.filter(owner=request.user).exclude(pages__in=page_id)
        return utils.render_with_request_context(request, "choose_picture.html",
                {'album_id':album_id, 'page_id':page_id, 'pictures':pictures })
        
    elif album_id:
        #Build a page addition form
        album=Album.objects.get(owner=request.user, id=album_id)
        if request.method == "POST":
            page = Page(album=album)
            form = forms.AddPageForm(request.POST, instance=page)
            if form.is_valid():
                page = form.save()
                page_num = album.page_set.count()
                return redirect_to(request,reverse('show_page', kwargs={'album_id':album.id,'page_number':page_num}), False)
        else:
            form=forms.AddPageForm()
        rcontext["header"] = "Add a new page to album "+album.name
        rcontext["action"] = reverse("add_page", kwargs={"album_id":album.id})
        rcontext["caption"] = "Page information"
        rcontext["submit"] = "Add"
        
    else:
        #Build an album addition form
        if request.method == "POST":
            album = Album(owner=request.user)
            form = forms.CreateAlbumForm(request.POST,instance=album)
            if form.is_valid():
                album = form.save(commit=False)
                album.save()
                return redirect_to(request, reverse('show_album', kwargs={'album_id':album.id}), False)
        else:
            form = forms.CreateAlbumForm()
        form.fields['cover_picture'].queryset = Picture.objects.filter(owner=request.user)
        rcontext["header"] = "Add a new album"
        rcontext["action"] = reverse("add_album")
        rcontext["caption"] = "Album information"
        rcontext["submit"] = "Create"

    #Build rest of the request context for the generic form template
    rcontext['form'] = form
    rcontext["form_class"] = "generated"
    return utils.render_with_request_context(request, "generic_caption_form.html",rcontext);

@login_required
def add_new_picture(request):
    if request.method == "POST":
        picture = Picture(owner=request.user)
        form = forms.AddPictureForm(request.POST, instance = picture)
        if form.is_valid():
            picture = form.save()
            return redirect_to(request, reverse('show_pictures'), False)
    else:
        form = forms.AddPictureForm()
    #Build the request context for the generic form template
    rcontext = {"form":form}
    rcontext["form_class"] = "generated"
    rcontext["header"] = "Add a new picture"
    rcontext["caption"] = "Picture information"
    rcontext["submit"] = "Add"
    return utils.render_with_request_context(request, "generic_caption_form.html",rcontext);

@login_required 
def upload_picture(request):
    if request.method == "POST":
        picture = Picture(owner=request.user)
        form = forms.UploadPictureForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture = form.save(commit=False)
            filename = request.FILES['file'].name
            picture.name = form.cleaned_data['name'] + filename[filename.rfind('.'):]
            utils.handle_upload(request.FILES['file'], request.user.username, picture.name)
            picture.uri = settings.MEDIA_URL + request.user.username + '/' + picture.name
            picture.save()
            return redirect_to(request, reverse('show_pictures'), False)
    else:
        form = forms.UploadPictureForm()
    #Build the request context for the generic form template
    rcontext = {"form":form}
    rcontext["header"] = "Upload a picture"
    rcontext["action"] = reverse("upload_new_picture")
    rcontext["caption"] = "Upload picture information"
    rcontext["submit"] = "Upload"
    return utils.render_with_request_context(request, "generic_caption_form.html",rcontext);

@login_required
def delete_picture(request, picture_id):
    try:
        pictures = Picture.objects.filter(owner=request.user)
        picture = Picture.objects.get(id=picture_id, owner=request.user)
        print picture.name
        path = os.path.join(settings.MEDIA_ROOT, request.user.username, picture.name)
        print path
        if os.path.exists(path):
            os.remove(path)
        picture.delete()
        return utils.render_with_request_context(request,"all_pictures.html",
                                       {'pictures':pictures,"deleted_picture":picture})
    except Picture.DoesNotExist:
        raise Http404("Could not find the given picture")

@login_required
def public_link(request, album_id, remove=False):
    try:
        album = Album.objects.get(owner=request.user, id=album_id)
    except Album.DoesNotExist:
        raise Http404
    
    if remove:
        album.public_token = ""
    else:
        utils.generate_public_token(album) 
    #save the changes        
    album.save()
    
    return redirect_to(request, reverse('show_album', kwargs={'album_id':album.id}), False)
   
@login_required
def post_to_facebook(request, album_id, page_number=1):

    #extract parameters from the call
    user = request.user.social_auth.get()
    access_token = user.extra_data['access_token']
    user_id = user.extra_data['id']

    try:
        album = Album.objects.get(id=album_id)
    except Album.DoesNotExist:
        raise Http404("Could not find the album")

    # Make the link to be posted
    if album.public:
        public_link = request.build_absolute_uri(reverse("show_album", kwargs={'album_id':album.id}))
    elif album.owner == request.user:
        # generate public token if there isn't one
        if not album.public_token:
            utils.generate_public_token(album)
            album.save()
        public_link = request.build_absolute_uri(reverse("show_album", kwargs={'album_id':album.id})) + "?public_token=%s" % album.public_token
    else:
        raise Http404("Not your album")

    # Make the request to post to facebookpage
    parameters = {'access_token':access_token, 'link':public_link}
    url = "https://graph.facebook.com/{0}/feed".format(user_id)
    headers = {'Content-Type':'multipart/form-data'}
    data = urllib.urlencode(parameters)
    req = urllib2.Request(url, data, headers)
    try:
        response = urllib2.urlopen(req)
        success = True
    except urllib2.URLError, e:
        success = False

    pages = get_pages(request,album.page_set, page_number)

    return render_with_request_context(request,"social_result.html", {"success":success, "pages":pages, "album":album})

#def add_caption(request):
#    if request.method == "POST":
#        print request.POST
#        page_id = request.POST.get("page_id")
#        caption = request.POST.get("caption")
#        print page_id
#        print caption
#        page = Page.objects.get(id=page_id)
#        page.extra_caption = caption
#        page.save()
